<template>
  <div>
    <div class="city-search">
      <input v-model="keyword" type="text" class="city-search-input" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content" ref="content"
    v-show="keyword">
      <ul>
        <li 
        class="search-item border-bottom" v-for="item in list" 
        :key="item.id"
        @click="handleCityClick(item.name)">
            {{item.name}}
        </li>
        <li
        class="search-item border-bottom" 
        v-show="hasNoData">
            沒有找到匹配数据
        </li>

      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
import { mapMutations } from 'vuex'
export default {
  name: "CitySearch",
  props:{
      cities:{
          type:Object,
          default:{}
      }
  },
  data () {
      return {
          keyword:'',
          list:[],
          timer:null
      }
  },
  computed: {
      hasNoData(){
          return !this.list.length
      }
  },
  watch: {
      keyword () {
          if(this.timer) {
              clearTimeout(this.timer)
          }
          if(this.keyword) {
              this.list = []
          }
          this.timer = setTimeout(() =>{
              const result = []
              for (let i in this.cities) {
                  this.cities[i].forEach( value =>{
                      if(value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1){
                          result.push(value)
                      }
                  })
              }
              this.list = result
          },100)
      }
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.content);
  },
   methods:{
    handleCityClick(city){
      // 这种写法是通过分发action来间接调用Mutations 
      // this.$store.dispatch('updataCity',city)
      // 这种方法是直接调用Mutations   下面这句话相当于this.$store.commit('UPDATE_CITY',city)
      this.UPDATE_CITY(city)
      this.$router.push('/')
    },
    ...mapMutations(['UPDATE_CITY']),
  }

};
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.city-search {
  height: 0.72rem;
  padding: 0 0.1rem;
  background: $bgColor;

  .city-search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    line-height: 0.62rem;
    padding: 0 0.1rem;
    border-radius: 0.06rem;
    color: #666;
    text-align: center;
  }
}

.search-content
    position: absolute
    top: 1.6rem
    left: 0
    right: 0
    bottom: 0
    z-index: 1
    overflow: hidden
    text-align: left
    background: #eee
    .search-item
        line-height: .62rem
        padding-left: .2rem
        background: #fff
        color: #666
</style>